#!/usr/bin/python 
#   yongming.li

import re
import string
import os
import time
import  sys

from Cpuinfo import *
from CPUChart import *

cpufilename='cpu.csv'

def writefile(name,buf,isreturn):

    f = file(name, 'a') # open for 'w'riting
    f.write(buf) # write text to file
    if isreturn != 0:
        f.write('\r\n' ) # write text to file
    f.close()
    return;

cpucontainer = {}

#User 2%, System 4%, IOW 0%, IRQ 0%
#User 13 + Nice 0 + Sys 31 + Idle 579 + IOW 0 + IRQ 0 + SIRQ 0 = 623

def  parsecpu (s): 
    s=s.strip()

    if 'Nice' not in s:
        return -1 
    print s
    cpuitem=string.split(s)

    cpuinfo = Cpuinfo(cpuitem[1],cpuitem[4],cpuitem[7],cpuitem[10],cpuitem[13],cpuitem[16],cpuitem[19],cpuitem[21]);

    cpuinfo.dumpCpuinfo();
    cpurate = cpuinfo.getCPUrate();
    print cpurate

    cpumeter = CPUMeter();
    cpumeter.showroundmeter();
    cpumeter.showsimpleline();

    return 0;

#   -n num  Updates to show before exiting.\n
#   -d num  Seconds to wait between updates.\n
def startcpu():
    while True:
        print 'startcpu ......'
        f = file('cpu.csv', 'w') # open for 'w'riting
        f.close()
        regsfile = os.popen('adb shell top -d 1 -n 1').readlines()
        if regsfile:
           print 'adb shell successful'
        else:
           print  'adb shell failed'
           sys.exit(0)

        for  line  in regsfile: 
            if len (line) == 0  or  len (line) <= 3:  # Zero length indicates EOF 
                continue  
            if(parsecpu(line)==0):
                break; 
        print  '--------------------------------------------------------------------'

        #time.sleep(5)
##############################################################################################################

if __name__ == '__main__':
    #cpuinfo = Cpuinfo();
    #cpuinfo.dumpCpuinfo();
    startcpu()

version =  '0.2'  


def cpumeterhelp():
    helpInfo = """
Build Environment Requirement
=============================================================
* ********* Suggested OS and Tool Chain to install *********
*
*       OS                         : Linux distribution Ubuntu 10.04
*       Memory Size                : 4G or above
*       make                       : GNU Make 3.81 or 3.82
*       perl                       : Version 5.10.X
*       python                     : Version 2.6.X
*       arm-linux-androideabi-gcc  : Version 4.6.X
*       gcc                        : Version 4.4.3
*       jdk                        : Version 1.6.X
*       bison                      : Version 2.4.X
*       flex                       : Version 2.5.X
*       gperf                      : Version 3.0.X
*       mingw                      : Installed
*       unix2dos/tofrodos          : Installed
* **********************************************************
=============================================================

"""


